package com.abel.amq.spring.service.impl;

import com.abel.amq.spring.entity.MailContent;
import com.abel.amq.spring.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * @author abel.he
 * @data 2018/8/8 15:40
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Autowired
    JmsTemplate jmsTemplate;

    @Override
    public void sendMessage(String from, String to, String subject, String content) {
        System.out.println(jmsTemplate);

        if (to.indexOf(";") > -1) {
            String[] arrTo = to.split(";");
            for (String t :
                    arrTo) {
                if (null == t || "".equals(t.trim())) {
                    continue;
                }
                final MailContent mailContent = transDataToObject(from, t, subject, content);
                sendMail(mailContent);
            }
        } else {
            final  MailContent mailContent = transDataToObject(from, to, subject, content);
            sendMail(mailContent);
        }

    }

    private void sendMail(final MailContent mailContent) {
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                Message message = session.createObjectMessage(mailContent);
                return message;
            }
        });
    }

    private MailContent transDataToObject(String from, String t, String subject, String content) {
        MailContent mailContent = new MailContent();
        mailContent.setFrom(from);
        mailContent.setTo(t);
        mailContent.setSubject(subject);
        mailContent.setContent(content);
        return mailContent;
    }
}
